package com.pekall.market.download;


import android.util.Log;

import com.pekall.market.activity.DownloadPresenterImpl;
import com.pekall.market.application.MarketClassTwoApplication;
import com.pekall.market.bean.AppListInfo;
import com.pekall.market.db.Dao.AppInfoDao;
import com.pekall.market.service.PoliceMarketService;
import com.pekall.market.util.L;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 用于在Http请求开始时，自动显示一个ProgressDialog
 * 在Http请求结束是，关闭ProgressDialog
 * 调用者自己对请求数据进行处理
 * Created by WZG on 2016/7/16.
 */
public class ProgressDownSubscriber<T> extends Subscriber<T> implements DownloadProgressListener {
    //弱引用结果回调
    /*下载数据*/
    private DownInfo downInfo;
    private long pre_progress = 0;//上一次通知的下载进度
    public static List<HttpProgressListener> mHttpProgressListenerList;

    /**
     * 注册下载回调监听器
     *
     * @param pHttpProgressListener
     */
    public static void registerHttpProgressListener(HttpProgressListener pHttpProgressListener) {
        if (mHttpProgressListenerList == null) {
            mHttpProgressListenerList = new ArrayList<>();
        }
        if (!mHttpProgressListenerList.contains(pHttpProgressListener)) {
            mHttpProgressListenerList.add(pHttpProgressListener);
        }
    }

    /**
     * 注销下载回调监听器
     *
     * @param pHttpProgressListener
     */
    public static void unregisterHttpProgressListener(HttpProgressListener pHttpProgressListener) {
        if (mHttpProgressListenerList == null) {
            return;
        }
        if (mHttpProgressListenerList.contains(pHttpProgressListener)) {
            mHttpProgressListenerList.remove(pHttpProgressListener);
        }
    }


    private static final int REFRESHUI_INTERVAL = 1;

    public ProgressDownSubscriber(DownInfo downInfo) {
        this.downInfo = downInfo;
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        downInfo.setState(DownState.START);
        if (mHttpProgressListenerList != null) {
            for (HttpProgressListener listener : mHttpProgressListenerList) {
                listener.onStart(downInfo);
            }
        }
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {
        downInfo.setState(DownState.FINISH);
        HttpDownManager.getInstance().downCompleted(downInfo);
        if (mHttpProgressListenerList != null && !mHttpProgressListenerList.isEmpty()) {
            for (HttpProgressListener listener : mHttpProgressListenerList) {
                listener.onComplete(downInfo);
            }
        }
    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        Log.e("yh------------", "ProgressDownSubscriber.onError错误:" + e.getMessage());
        /*停止下载*/
        downInfo.setState(DownState.ERROR);
        HttpDownManager.getInstance().stopDownOnError(downInfo);
        if (mHttpProgressListenerList != null && !mHttpProgressListenerList.isEmpty()) {
            for (HttpProgressListener listener : mHttpProgressListenerList) {
                listener.onError(downInfo, e);
            }
        }
    }

    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param t 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T t) {

    }

    /**
     * 更新界面，保存参数(读取位置)
     *
     * @param readSize 网络返回的字节数
     * @param count    剩余文件大小
     * @param done
     */

    @Override
    public void update(long readSize, long count, boolean done) {
        if (downInfo.getCountLength() > count) {
            //经过计算，readSize变成了文件读取长度.(文件读取长度=文件总长-文件剩余长度+实际网络读取的字节数)
            readSize = downInfo.getCountLength() - count + readSize;
        } else {
            //设置文件总长度
            downInfo.setCountLength(count);
        }
        //文件读取长度
        downInfo.setReadLength(readSize);
        //下载进度=文件读取长度/文件总长度
        int downSchedule = (int) (downInfo.getReadLength() * 100 / downInfo.getCountLength());

        Log.w("yh----", ",下载进度=" + downSchedule);

        Log.w("yh----", "update_总大小=" + (downInfo.getReadLength() + (downInfo.getCountLength() - downInfo.getReadLength())));
        int progress = ((AppListInfo.ContentBean) downInfo).getFileSize() > 0 ? ((int) (downInfo.getReadLength() * 100 / ((AppListInfo.ContentBean) downInfo).getFileSize())) : 0;
        if (((AppListInfo.ContentBean) downInfo).getFileSize() > 0  //避免除数为0的异常
                && progress - pre_progress >= REFRESHUI_INTERVAL) {//判断进度是否增长了REFRESHUI_INTERVAL
            pre_progress = progress;
            downInfo.setState(DownState.DOWN);
            AppInfoDao.getInstance().createOrUpdate((AppListInfo.ContentBean) downInfo);

            rx.Observable.just(readSize).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                      /*如果暂停或者停止状态延迟，不需要继续发送回调，影响显示*/
                            if (downInfo.getState() == DownState.PAUSE || downInfo.getState() == DownState.STOP)
                                return;

                            if (mHttpProgressListenerList != null && !mHttpProgressListenerList.isEmpty()) {
                                for (HttpProgressListener listener : mHttpProgressListenerList) {
                                    listener.updateProgress(downInfo, aLong, downInfo.getCountLength());
                                }
                            }
                        }
                    });
        }
    }
}